package com.qw.soul.permission;

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;

import com.qw.soul.permission.debug.PermissionDebug;
import com.qw.soul.permission.exception.ContainerStatusException;
import com.qw.soul.permission.exception.InitException;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Stack;


/**
 * @author cd5160866
 */
public class PermissionActivityManager implements Application.ActivityLifecycleCallbacks
{

    private static final String TAG = PermissionActivityManager.class.getSimpleName();

    private List<Activity> activities = new ArrayList<>();

    private static PermissionActivityManager instance;

    public static PermissionActivityManager getInstance()
    {
        if(instance == null)
        {
            synchronized(PermissionActivityManager.class)
            {
                if(instance == null)
                {
                    instance = new PermissionActivityManager();
                }
            }
        }
        return instance;
    }

    public void init(Application app)
    {
        app.unregisterActivityLifecycleCallbacks(this);
        app.registerActivityLifecycleCallbacks(this);
    }

    /**
     * 获取可用Activity
     *
     * @return Activity 优先栈顶
     * @throws InitException            初始化失败
     * @throws ContainerStatusException Activity状态异常
     */
    public Activity getTopActivity()
    {
        if (activities.size() > 0)
        {
            for (int i = activities.size() - 1; i >= 0; i--)
            {
                Activity activity = activities.get(i);
                if (PermissionTools.isActivityAvailable(activity))
                {
                    return activity;
                }
            }
        }
        return null;
    }

    public synchronized void push(Activity activity)
    {
        activities.add(activity);
    }

    /***
     * 弹出顶层activity，同时会从栈中移除，一般用于activity销毁时调用
     * @return
     */
    public void pop(Activity activity)
    {
        if (activities.size() > 0)
        {
            activities.remove(activity);
        }
    }


    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState)
    {
        push(activity);
    }

    @Override
    public void onActivityStarted(Activity activity)
    {
    }

    @Override
    public void onActivityResumed(Activity activity)
    {
    }

    @Override
    public void onActivityPaused(Activity activity)
    {

    }

    @Override
    public void onActivityStopped(Activity activity)
    {

    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState)
    {

    }

    @Override
    public void onActivityDestroyed(Activity activity)
    {
        pop(activity);
    }
}
